/**
 * 
 */
package it.hive.io.downloader;

import it.hive.io.constants.IO_Constants;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javafx.beans.property.SimpleBooleanProperty;
import javafx.concurrent.Task;

import org.apache.commons.lang3.StringUtils;

/**
 * @author 04400099
 * 
 */
public class Downloader extends Task<File> {
	private URL url;
	private String localFileName;
	private SimpleBooleanProperty downloadCompletato;

	public Downloader(URL url, String path, String fileName) {
		this.url = url;
		this.localFileName = path + verificaNomeFile(fileName);
		downloadCompletato = new SimpleBooleanProperty();
	}

	private String verificaNomeFile(String fileName) {
		if (StringUtils.isBlank(fileName)) {
			return "download.mp3";
		} else {
			return fileName.replace("\\", "-").replace("/", "-");
		}
	}

	public static File downloadFileFromURL(URL url) throws IOException {
		return downloadFileFromURL(url, IO_Constants.TMP_FILE, null);
	}

	public static File downloadFileFromURL(URL url, String localFilename, String userAgent) throws IOException {
		InputStream is = null;
		FileOutputStream fos = null;
		try {
			URLConnection urlConn = url.openConnection();
			if (userAgent != null) {
				urlConn.setRequestProperty("User-Agent", userAgent);
			}
			is = urlConn.getInputStream();
			fos = new FileOutputStream(localFilename, false);
			byte[] buffer = new byte[4096];
			int len;
			while ((len = is.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} finally {
				if (fos != null) {
					fos.close();
				}
			}
		}

		return new File(localFilename);
	}

	@Override
	protected File call() throws Exception {
		running();
		downloadCompletato.set(false);
		InputStream is = null;
		FileOutputStream fos = null;
		animazioneTesto(getMessage(), "Avvio Download . . .").join();
		try {
			URLConnection urlConn = url.openConnection();
			is = urlConn.getInputStream();
			fos = new FileOutputStream(localFileName, false);
			long fileSize = urlConn.getContentLength();
			byte[] buffer = new byte[4096];
			int len;
			int progress = 0;
			while ((len = is.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
				progress += len;
				updateProgress(progress, fileSize);
			}
		} catch (IOException e) {
			e.getMessage();
		} finally {
			try {
				if (is != null) {
					is.close();
				}
			} finally {
				if (fos != null) {
					fos.close();
				}
			}
		}
		done();
		animazioneTesto(getMessage(), "Download Completato!                ").join();
		downloadCompletato.set(true);
		animazioneTesto(getMessage(), "M2O Reloaded - Download & Play").join();
		return new File(localFileName);
	}

	public SimpleBooleanProperty downloadCompletatoProperty() {
		return downloadCompletato;
	}

	private Thread animazioneTesto(final String oldString, final String newText) {
		Thread t = new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = oldString.length(); i != 0; i--) {
					updateMessage(oldString.substring(0, i));
					try {
						Thread.sleep(10);
					} catch (InterruptedException e) {
						System.out.println(e.getMessage());
					}
				}
				for (int i = 0; i <= newText.length(); i++) {
					updateMessage(newText.substring(0, i));
					try {
						Thread.sleep(20);
					} catch (InterruptedException e) {
					}
				}
			}
		});
		t.start();
		return t;
	}

}
